<template>
  <div class="page_contact" id="contact_page">
    <div class="warp">
      <div class="container">
        <div class="row">
          <div class="col-12">
            <!-- 标题 -->
            <div class="contact_title">
              <div class="title_bar"></div>
              <h2>{{ t('contactUs') }}</h2>
            </div>
            
            <div class="contact_content">
              <div class="row">
                <!-- 左侧联系信息 -->
                <div class="col-12 col-md-4 contact_info">
                  <div class="info_item">
                    <strong>{{ t('contactCompany') }}：</strong>
                    <p>遇见科技(武汉)有限公司</p>
                  </div>
                  <div class="info_item">
                    <strong>{{ t('contactAddress') }}：</strong>
                    <p>武汉市洪山区创业街73号武汉留学生创业园 A栋3216室</p>
                  </div>
                  <div class="info_item">
                    <strong>{{ t('contactEmail') }}：</strong>
                    <p><a href="mailto:yjkj2303@qq.com">yjkj2303@qq.com</a></p>
                  </div>
                  <div class="info_item">
                    <strong>{{ t('contactWebsite') }}：</strong>
                    <p><a href="https://www.1000help.com/" target="_blank">www.1000help.com</a></p>
                  </div>
                </div>
                
                <!-- 中间表单 -->
                <div class="col-12 col-md-5 contact_form">
                  <form @submit.prevent="submitForm">
                    <div class="form-group">
                      <label>{{ t('messageTitle') }} <span class="required">*</span></label>
                      <input 
                        type="text" 
                        v-model.trim="form.title" 
                        :placeholder="t('messageTitle')"
                        required
                        maxlength="200"
                      />
                    </div>
                    
                    <div class="form-group">
                      <label>{{ t('messageContent') }} <span class="required">*</span></label>
                      <textarea 
                        v-model.trim="form.content" 
                        :placeholder="t('messageContent')"
                        rows="6"
                        required
                      ></textarea>
                    </div>
                    
                    <div class="form-group">
                      <label>{{ t('yourEmail') }} <span class="required">*</span></label>
                      <input 
                        type="email" 
                        v-model.trim="form.email" 
                        :placeholder="t('yourEmail')"
                        required
                        maxlength="100"
                      />
                    </div>
                    
                    <div class="form-group" v-if="captchaUrl">
                      <label>{{ t('verificationCode') }} <span class="required">*</span></label>
                      <div class="captcha_row">
                        <input 
                          type="text" 
                          v-model.trim="form.captcha" 
                          :placeholder="t('verificationCode')"
                          required
                          maxlength="4"
                          class="captcha_input"
                        />
                        <img 
                          ref="captchaImg"
                          :src="captchaImageUrl" 
                          @click="refreshCaptcha" 
                          @error="handleCaptchaError"
                          alt="验证码" 
                          class="captcha_img"
                          title="点击刷新验证码"
                          :key="captchaRefreshKey"
                        />
                      </div>
                    </div>
                    
                    <button type="submit" class="btn_submit" :disabled="submitting">
                      {{ submitting ? t('submitting') || '提交中...' : t('submitMessage') }}
                    </button>
                  </form>
                </div>
                
                <!-- 右侧二维码 -->
                <div class="col-12 col-md-3 contact_qr">
                  <div class="qr_code_box">
                    <img src="/img/qrcode_img.png" alt="QR Code" class="qr_code_img" @error="handleQRCodeError" />
                    <p class="qr_code_text">{{ t('scanQRCode') }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import mixin from "@/mixins/page.js";
import mixinI18n from "@/mixins/i18n.js";

export default {
  mixins: [mixin, mixinI18n],
  data() {
    return {
      form: {
        title: '',
        content: '',
        email: '',
        captcha: ''
      },
      captchaUrl: '',
      captchaId: '',
      submitting: false,
      captchaRefreshKey: 0
    };
  },
  computed: {
    /**
     * 计算验证码图片URL
     */
    captchaImageUrl() {
      if (!this.captchaUrl) return '';
      
      let url = String(this.captchaUrl);
      
      // 移除所有 ~/ 前缀（包括 ~/api/）
      url = url.replace(/^~+\//, '/');
      
      // 确保URL以 /api/captcha/get 开头
      // 如果URL不包含 /api/captcha/get，重新构造
      if (!url.includes('/api/captcha/get')) {
        // 提取查询参数
        const queryIndex = url.indexOf('?');
        const query = queryIndex !== -1 ? url.substring(queryIndex) : '';
        url = '/api/captcha/get' + query;
      }
      
      // 确保URL以 /api/ 开头（不是 ~/api/）
      if (url.indexOf('/api/') !== 0) {
        url = url.replace(/^.*?\/api\//, '/api/');
      }
      
      // 调试：输出最终URL
      console.log('原始captchaUrl:', this.captchaUrl);
      console.log('处理后验证码URL:', url);
      
      return url;
    }
  },
  methods: {
    /**
     * 获取验证码
     */
    async getCaptcha() {
      try {
        // 生成随机ID
        this.captchaId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        // 调用后端API获取验证码图片
        // 使用绝对路径 /api/captcha/get，这样会被Vue代理转发到后端
        // 使用时间戳和随机数确保每次获取都是新的验证码，避免浏览器缓存
        const timestamp = Date.now();
        const random = Math.random().toString(36).substr(2, 9);
        // 直接设置URL，确保不包含 ~ 符号
        this.captchaUrl = `/api/captcha/get?t=${this.captchaId}&_=${timestamp}&r=${random}`;
        
        console.log('设置的captchaUrl:', this.captchaUrl);
        
        // 确保URL被正确设置
        this.$nextTick(() => {
          // 强制更新图片URL
          if (this.$refs.captchaImg) {
            const finalUrl = this.captchaImageUrl;
            console.log('设置img.src为:', finalUrl);
            this.$refs.captchaImg.src = finalUrl;
          }
        });
      } catch (error) {
        console.error('获取验证码失败:', error);
        this.captchaUrl = '';
      }
    },
    
    /**
     * 刷新验证码
     */
    refreshCaptcha() {
      this.form.captcha = '';
      // 增加刷新key，强制Vue重新渲染img标签
      this.captchaRefreshKey++;
      this.getCaptcha();
    },
    
    /**
     * 处理验证码图片加载错误
     */
    handleCaptchaError(event) {
      console.error('验证码加载失败，尝试重新获取');
      // 如果验证码加载失败，自动重新获取
      setTimeout(() => {
        this.refreshCaptcha();
      }, 500);
    },
    
    /**
     * 处理二维码图片加载错误
     */
    handleQRCodeError(event) {
      // 如果主要图片加载失败，尝试使用备用图片
      if (event.target.src.indexOf('qrcode_img.png') !== -1) {
        event.target.src = '/img/wx.png';
      }
    },
    
    /**
     * 提交表单
     */
    async submitForm() {
      if (this.submitting) return;
      
      // 验证必填项
      if (!this.form.title || !this.form.content || !this.form.email) {
        this.$toast(this.t('contentCannotBeEmpty') || '请填写完整信息', 'warning');
        return;
      }
      
      // 如果验证码字段存在，验证验证码
      if (this.captchaUrl && !this.form.captcha) {
        this.$toast(this.t('verificationCode') + '不能为空', 'warning');
        return;
      }
      
      // 验证邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(this.form.email)) {
        this.$toast('请输入正确的邮箱地址', 'warning');
        return;
      }
      
      this.submitting = true;
      
      try {
        const res = await this.$post("~/api/feedback/add?", {
          title: this.form.title,
          content: this.form.content,
          email: this.form.email,
          captcha: this.form.captcha,
          captcha_id: this.captchaId
        });
        
        if (res.result) {
          this.$toast(this.t('messageSubmitted') || '留言提交成功！', 'success');
          // 清空表单
          this.form = {
            title: '',
            content: '',
            email: '',
            captcha: ''
          };
          // 刷新验证码
          this.refreshCaptcha();
        } else if (res.error) {
          this.$toast(res.error.message || '提交失败，请重试', 'danger');
          // 如果验证码错误，刷新验证码
          if (res.error.message && res.error.message.includes('验证码')) {
            this.refreshCaptcha();
          }
        } else {
          this.$toast('服务器连接失败，请重试', 'danger');
        }
      } catch (error) {
        console.error('提交失败:', error);
        this.$toast('提交失败，请重试', 'danger');
      } finally {
        this.submitting = false;
      }
    }
  },
  mounted() {
    this.getCaptcha();
  }
};
</script>

<style scoped>
.page_contact {
  padding: 2rem 0;
  min-height: 600px;
}

.contact_title {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
  padding-left: 1rem;
}

.title_bar {
  width: 4px;
  height: 2rem;
  background-color: #409eff;
  margin-right: 1rem;
}

.contact_title h2 {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 600;
  color: #333;
}

/* 二维码区域（右侧） */
.contact_qr {
  padding: 1.5rem;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.qr_code_box {
  text-align: center;
  padding: 1rem;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.qr_code_img {
  width: 150px;
  height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: white;
}

.qr_code_text {
  margin-top: 0.75rem;
  font-size: 0.875rem;
  color: #666;
  line-height: 1.5;
}

.contact_content {
  padding: 2rem;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.contact_info {
  padding: 1.5rem;
}

.info_item {
  margin-bottom: 1.5rem;
}

.info_item strong {
  display: block;
  margin-bottom: 0.5rem;
  color: #333;
  font-size: 1rem;
}

.info_item p {
  margin: 0;
  color: #666;
  line-height: 1.6;
  word-break: break-word;
}

.info_item a {
  color: #409eff;
  text-decoration: none;
}

.info_item a:hover {
  text-decoration: underline;
}

.contact_form {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #333;
  font-weight: 500;
}

.required {
  color: #f56c6c;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #409eff;
}

.form-group textarea {
  resize: vertical;
  min-height: 120px;
}

.captcha_row {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.captcha_input {
  flex: 1;
}

.captcha_img {
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 2px;
  background-color: #f5f7fa;
}

.captcha_img:hover {
  border-color: #409eff;
}

.btn_submit {
  width: 100%;
  padding: 0.875rem;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn_submit:hover:not(:disabled) {
  background-color: #66b1ff;
}

.btn_submit:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .contact_content .row > div {
    margin-bottom: 2rem;
  }
  
  .contact_title h2 {
    font-size: 1.5rem;
  }
  
  .qr_code_img {
    width: 120px;
    height: 120px;
  }
}
</style>

